package com.itheima.controller;


import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberController {
    //本地注入
    @Autowired
    private JedisPool jedisPool;
    //远程注入
    @Reference
    private MemberService memberService;

    //登入方法
    @RequestMapping("/login")
    public Result login(HttpServletResponse response, @RequestBody Map map){
        String telephone = (String)map.get("telephone");
        //从 Redis 中获取存储的验证码
       //String validateCodeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
       //接受从前端页面传来的验证码
        String validateCode = (String)map.get("validateCode");
       // if (validateCode != null && validateCodeInRedis!=null && validateCode.equals(validateCodeInRedis)){
        Member member;
        if (validateCode != null){
            //验证码输入正确
            //按手机号查找数据库套餐

            member = memberService.findByTelephone(telephone);
            //判断当前用户是否是我们的会员
        if(member == null){
           //不是会员 为其创建会员
            //为套餐增加数据
            member.setRegTime(new Date());
            member.setPhoneNumber(telephone);
            memberService.addMember(member);
        }
         //将用户信息通过浏览器写入Cookie
            Cookie cookie=new Cookie("login_member_telephone",telephone);
          cookie.setPath("/");
          cookie.setMaxAge(60*60*24*30);
          response.addCookie(cookie);

          //将会员信息保存到 Redis
            String json= JSON.toJSON(member).toString();
            jedisPool.getResource().setex(telephone,60*30,json);
            return new Result(true,MessageConstant.LOGIN_SUCCESS);

        }else{
            //验证码输入错误
            return  new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }
}
